package com.examsystem.controller;

import com.alibaba.fastjson.JSON;
import com.examsystem.pojo.Question;
import com.examsystem.pojo.UserPaper;
import com.examsystem.service.QuestionService;
import com.examsystem.pojo.vo.Result;
import com.examsystem.service.UserPaperService;
import com.examsystem.pojo.vo.LoginUser;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author fire'ge
 */
@Controller
@RequestMapping("/question")
public class QuestionController {
    @Resource
    private QuestionService questionService;
    @Resource
    private UserPaperService userPaperService;


    /*
    学生端代码
     */


    @PreAuthorize("hasAuthority('question:queryQueData')")
    @ResponseBody
    @RequestMapping(value = "/queryQueData/{paperId}",produces = "application/json;charset=utf-8")
    public String queryQueData(@PathVariable int paperId) {
        LoginUser user = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            //添加该用户的userPaper，主要用来记录考试的状态
            int userId = user.getUser().getUserId();
            userPaperService.addUserPaper(new UserPaper(0, paperId, userId, 0, 0));
            //查询好试卷数据返回给前端
            List<Question> questions = questionService.queryQuestionsByPaperIdAndUserId(paperId,user.getUser().getUserId());
            return JSON.toJSONString(Result.succ(questions));
        }



    /*
    教师端代码
     */

    /**
     * 添加试题
     * @param question  试题对象
     * @return  result结果集对象
     */
    @PreAuthorize("hasAuthority('teacher')")
    @RequestMapping("/addQuestion")
    @ResponseBody
    public Result addQuestion(@RequestBody Question question){
        return questionService.addQuestion(question);
    }

    /**
     * 给试题添加答案/解析【图片类】
     * @param imgA  答案图片
     * @param imgP  解析图片
     * @param questionId  试题id
     * @return  result结果集对象
     */
    @RequestMapping("/addQuestionPic/{questionId}")
    @ResponseBody
    public Result addQuestionPic(@RequestParam("imgA") MultipartFile imgA, @RequestParam("imgP") MultipartFile imgP,@PathVariable int questionId){
        return questionService.addQuestionPic(imgA, imgP, questionId);
    }

    /**
     * 整张试卷的所有questionId
     * @param paperId  试卷id
     * @return  result结果集对象【主要是list集合的questionId】
     */
    @RequestMapping("/paperQuestionId")
    @ResponseBody
    public Result paperQuestionId(int paperId){
        return Result.succ(questionService.showQuestionIds(paperId));
    }
}
